
import { _decorator, Node, Vec3, v3 } from 'cc';
import Action3dManager, { ActionMngType } from '../../Script/Common/Action3dManager';
import yyComponent from '../../Script/Common/yyComponent';
import { EventType } from '../../Script/GameSpecial/GameEventType';
import { BreakItemAnim } from './BreakItemAnim';
const { ccclass, property } = _decorator;

@ccclass('BreakAnim')
export class BreakAnim extends yyComponent {
    //动画最长时间
    @property
    protected animMaxTime = 1.5;

    protected _childCmps: BreakItemAnim[] = [];
    protected _curT = 0;
    protected _isFinish = false;

    public init() {
        //初始化参数+初始化子节点
        this._childCmps = [];
        for (let i = 0; i < this.node.children.length; i++) {
            const e = this.node.children[i];
            const cmp = e.getComponent(BreakItemAnim);
            if (cmp) {
                cmp.init();
                this._childCmps.push(cmp);
            }
        }
    }

    //从对象池取出/回收时调用
    public reset() {
        this._childCmps.forEach(cmp => {
            cmp.reset();
        })
        this._curT = 0;
        this._isFinish = false;
    }
    //管理器调用
    public play() {
        this._isFinish = false;
        this.node.active = true;
        this._childCmps.forEach(cmp => {
            cmp && cmp.play();
        })
    }
    //管理器调用
    public customUpdate(dt) {
        if (this._isFinish) return;

        this._childCmps.forEach(cmp => {
            cmp && cmp.customUpdate(dt);
        })
        //动画计时器
        this._curT += dt;
        if (this._curT >= this.animMaxTime) {
            this._curT = 0;
            this.stop();
        }
    }

    //动画结束自己调用
    private stop() {
        if (this._isFinish) return;
        this._isFinish = true;
        this._childCmps.forEach(cmp => {
            if (cmp) {
                cmp.stopAllAnim();
            }
        })

        this.autoHide();
    }

    protected autoHide() {
        let move = Action3dManager.moveBy(2, 0, -0.5, 0);
        let cb = Action3dManager.callFun(this.onHideAnimFinish, this);
        let seq = Action3dManager.sequence(move, cb);
        Action3dManager.getMng(ActionMngType.Level).runAction(this.node, seq);
    }
    protected onHideAnimFinish() {
        this.emit(EventType.LevelEvent.removeBreakAnim, this);
    }

}

